package com.guanzhi.validation.validator;

import com.guanzhi.validation.annotation.CannotBlank;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * Spring6
 * <p> Package: com.guanzhi.validation.validator </p>
 * <p> File: CannotBlankValidator.java </p>
 * <p> Description:  (自定义校验 实现注解功能)</p>
 * <p> Date: 2024/9/21 19:47</p>
 *
 * @author LiKai
 * @version 1.0 （代码版本）
 * @email <a href="mailto:Likai55634@aliyun.com">LiKai</a>（邮箱）
 * @date 2024/9/21 19:47
 * @since jdk1.8（jdk版本）
 */
public class CannotBlankValidator implements ConstraintValidator<CannotBlank, String> {
    @Override
    public void initialize(CannotBlank constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        //null时不进行校验
        if (value != null && value.contains(" ")) {
            //获取默认提示信息
            String defaultConstraintMessageTemplate = constraintValidatorContext.getDefaultConstraintMessageTemplate();
            System.out.println("default message :" + defaultConstraintMessageTemplate);
            //禁用默认提示信息
            constraintValidatorContext.disableDefaultConstraintViolation();
            //设置提示语
            constraintValidatorContext.buildConstraintViolationWithTemplate("can not contains blank").addConstraintViolation();
            return false;
        }
        return true;
    }
}
